﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Wuther.Infrastructure.OpenAI;
using Wuther.Infrastructure.SMS;

namespace Wuther.Infrastructure.Controllers
{
    /// <summary>
    /// 手机验证码
    /// </summary>
    [RemoteService]
    [Area("SMS")]
    [Route($"api/{InfrastructureRemoteServiceConsts.ModuleName}/sms")]
    public class SmsController: InfrastructureController, ISmsService
    {
        private readonly ISmsService _service;
        private IHttpClientFactory _clientFactory;
        public SmsController(ISmsService service, IHttpClientFactory clientFactory)
        {
            _service = service;
            _clientFactory = clientFactory;
        }

        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("img")]
        public Task<CaptchaDto> GenerateCaptcha(GetCaptchaInput input)
        {
            return _service.GenerateCaptcha(input);
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("id")]
        public Task<string> GetVerificationCodeAsync(string phone)
        {
            return _service.GetVerificationCodeAsync(phone);
        }

        //[HttpGet]
        //[Route("chat")]
        //public async Task Chat(string msg)
        //{
        //    _httpContext.HttpContext.Response.Headers["Content-Type"] = "text/event-stream";
        //    _httpContext.HttpContext.Response.Headers["Cache-Control"] = "no-cache";
        //    _httpContext.HttpContext.Response.Headers["Connection"] = "keep-alive";
        //    //获取前端请求体
        //    using var reader = new StreamReader(_httpContext.HttpContext.Request.Body);
        //    var requestBody = await reader.ReadToEndAsync();

        //    // 创建转发到DeepSeek的请求
        //    var client = _clientFactory.CreateClient("DeepSeek");
        //    var request = new HttpRequestMessage(HttpMethod.Post, "v1/chat/completions")
        //    {
        //        Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
        //    };

        //    // 发送请求并获取流式响应
        //    using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        //    using var responseStream = await response.Content.ReadAsStreamAsync();
        //    using var streamReader = new StreamReader(responseStream);

        //    // 实时转发流式数据
        //    var buffer = new char[8192];
        //    int bytesRead;
        //    while ((bytesRead = await streamReader.ReadAsync(buffer, 0, buffer.Length)) > 0)
        //    {
        //        var chunk = new string(buffer, 0, bytesRead);
        //        await _httpContext.HttpContext.Response.WriteAsync(chunk);
        //        await _httpContext.HttpContext.Response.Body.FlushAsync();

        //        // 如果客户端断开连接则停止
        //        if (_httpContext.HttpContext.RequestAborted.IsCancellationRequested) break;
        //    }
        //}

        [HttpPost("getChat")]
        public async Task Chat()
        {

            // 获取请求体
            using var reader = new StreamReader(Request.Body);
            var requestBody = await reader.ReadToEndAsync();
            if (!string.IsNullOrEmpty(requestBody))
            {
                var model = new
                {
                    model = "deepseek-chat", // 替换为实际的模型名称
                    messages = new List<object>()
                    {
                        new
                        {
                             role = "user",
                             content="帮我写一首诗"

                        }
                    },
                    stream = true
                };
                requestBody = JsonConvert.SerializeObject(model);
            }

            // 创建DeepSeek请求
            var client = _clientFactory.CreateClient("DeepSeek");
            var request = new HttpRequestMessage(HttpMethod.Post, "/chat/completions")
            {
                Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
            };

            // 发送请求
            using var response = await client.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead);

            response.EnsureSuccessStatusCode();

            // 转发流
            using var responseStream = await response.Content.ReadAsStreamAsync();

            //await responseStream.CopyToAsync(context.Response.Body, 8192, context.RequestAborted);
            //await context.Response.Body.FlushAsync(context.RequestAborted);


            using var streamReader = new StreamReader(responseStream);
            var buffer = new char[16384];
            int bytesRead;

            while (!streamReader.EndOfStream)
            {
                try
                {
                    bytesRead = await streamReader.ReadAsync(buffer);
                    if (bytesRead > 0)
                    {
                        var chunk = new string(buffer, 0, bytesRead);
                        var lines = chunk.Split(new[] { "data:" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var item in lines)
                        {
                            var chunkObj = JsonConvert.DeserializeObject<ChatCompletionChunk>(item);
                            foreach (var content in chunkObj.Choices)
                            {
                                Console.Write(content.Delta.Content);
                            }
                        }
                        await Response.WriteAsync(chunk);
                        //await Response.Body.FlushAsync();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("流转发异常：" + ex);
                }

            }
        }

        [HttpPost("text")]
        public async Task Post()
        {
            string filePath = "D:\\image\\文档.txt";
            Response.ContentType = "application/octet-stream";
            var reader = new StreamReader(filePath);
            var buffer = new Memory<char>(new char[5]);
            int writeLength = 0;
            //每次读取5个字符写入到流中
            while ((writeLength = await reader.ReadBlockAsync(buffer)) > 0)
            {
                if (writeLength < buffer.Length)
                {
                    buffer = buffer[..writeLength];
                }
                await Response.WriteAsync(buffer.ToString());
                await Task.Delay(100);
            }
        }
    }
}
